package httpproxymiddleware

import (
	"errors"
	"go-gateway-learn/dao"
	"go-gateway-learn/middleware"
	"go-gateway-learn/reverseproxy"

	"github.com/gin-gonic/gin"
)

func HTTPReverseProxyMiddleware() gin.HandlerFunc{
	return func(c *gin.Context) {
		serverInterface,ok := c.Get("service")
		if !ok{
			middleware.ResponseError(c,2001, errors.New("service not found"))
			c.Abort()
			return
		}
		serviceDetail := serverInterface.(*dao.ServiceDetail)
		lb, err := dao.LoadBalancerHandler.GetLoadBalancer(serviceDetail)
		if err != nil{
			middleware.ResponseError(c, 2002, err)
			c.Abort()
			return
		}
		trans, err := dao.TransportorHandler.GetTrans(serviceDetail)
		if err != nil{
			middleware.ResponseError(c, 2003, err)
			c.Abort()
			return
		}
		proxy :=reverseproxy.NewLoadBalanceReverseProxy(c,lb, trans)
		proxy.ServeHTTP(c.Writer,c.Request)
	}
}